package com.byq.ai.agentlab.po;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import jakarta.persistence.Entity;
import jakarta.persistence.Id;
import org.springframework.ai.chat.messages.Message;
import org.springframework.ai.chat.messages.SystemMessage;

import java.util.ArrayList;
import  java.util.List;
@Entity//把下面这个class映射成一个数据库表，并且把成员变量映射成列
public class MyConversation {
    @Id
    String id;
    String userId;
    String messages;

    public String getMessages() {
        return messages;
    }

    public void setMessages(String messages) {
        this.messages = messages;
    }

    public String getId() {
        return id;
    }

    public void setId(String id) {
        this.id = id;
    }

    public String getUserId() {
        return userId;
    }

    public void setUserId(String userId) {
        this.userId = userId;
    }
    public Conversation toConversation(){
        ObjectMapper objectMapper = new ObjectMapper();
        List<MyMessage> mms = new ArrayList<>();
        try {
            // 2. 反序列化（JSON 字符串转对象）
             mms = objectMapper.readValue(messages, objectMapper.getTypeFactory().constructCollectionType(List.class, MyMessage.class));
        }catch (Exception e){

        }

        Conversation rst = new Conversation(id);
        List<Message> ms = new ArrayList<>();
        for(MyMessage m : mms){
            Message msg = m.toMessage();
            ms.add(msg);
        }
        rst.setMessages(ms);
        return  rst;

    }
    public void fromConversation(Conversation con) {
        this.id = con.id;
        List<MyMessage> mms = new ArrayList<>();
        for(Message m : con.getMessages()){
            MyMessage mm = new MyMessage();
            mm.fromMessage(m);
            mms.add(mm);
        }
        ObjectMapper objectMapper = new ObjectMapper();

        String json = null;
        try {
            json = objectMapper.writeValueAsString(mms);
        } catch (JsonProcessingException e) {
            throw new RuntimeException(e);
        }
        this.messages = json;




    }

}
